<template>
  <div>
    <el-card class="cardContainer">
      <div class="search">
        <el-input
          v-model="userName"
          placeholder="用户名"
          class="serachIpt"
        ></el-input>
        <el-button type="primary" @click="searchUser()">查询</el-button>
        <el-button @click="searchUser('clear')">清空</el-button>
      </div>
      <div class="addAndRemove">
        <el-button type="primary" @click="dialogForm()">添加</el-button>
        <el-button type="danger" @click="removeList">批量删除</el-button>
      </div>
      <!-- 添加用户dialog -->
      <el-dialog
        :title="addUserForm.id ? '修改用户' : '添加用户'"
        :visible.sync="dialogFormVisible"
        top="0"
      >
        <el-form :model="addUserForm" label-width="120px">
          <el-form-item label="用户名">
            <el-input
              v-model="addUserForm.username"
              autocomplete="off"
              size="medium"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户名昵称">
            <el-input
              v-model="addUserForm.nickName"
              autocomplete="off"
              size="medium"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户名密码" v-show="!addUserForm.id">
            <el-input
              v-model="addUserForm.password"
              autocomplete="off"
              size="medium"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addOrUpdateUser">确 定</el-button>
        </div>
      </el-dialog>

      <el-table
        :data="userInfo"
        border
        class="userTable"
        stripe
        :cell-style="rowStyle"
        :header-cell-style="rowStyle"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="序号" width="80" type="index"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="用户昵称" prop="nickName"></el-table-column>
        <el-table-column label="角色列表" prop="roleName"></el-table-column>
        <el-table-column label="创建时间" prop="gmtCreate"></el-table-column>
        <el-table-column label="更新时间" prop="gmtModified"></el-table-column>
        <el-table-column label="操作" v-slot="{ row, $index }">
          <el-button
            type="info"
            icon="el-icon-user-solid"
            size="mini"
            @click="getUserRoleInfo(row)"
          ></el-button>
          <el-button
            type="primary"
            @click="dialogForm(row)"
            size="mini"
            icon="el-icon-edit"
          ></el-button>
          <el-button
            type="danger"
            slot="reference"
            style="margin-left: 10px"
            size="mini"
            icon="el-icon-delete-solid"
            @click="removeUser(row)"
          ></el-button>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="getCalUserInfo"
        :current-page="page"
        :page-sizes="[5, , 7, 10, 15]"
        :page-size="limit"
        layout="  prev, pager,sizes, next,->, jumper,total"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 根据用户获取角色dialog -->
    <el-dialog title="设置角色" :visible.sync="userRoleDialogVisible" top="0">
      <el-form :model="addUserForm" label-width="120px">
        <el-form-item label="用户名">
          <el-input
            :value="roleUserName"
            autocomplete="off"
            size="medium"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="handleAssignRoles"
            @change="handleCheckedRouleChange"
          >
            <el-checkbox
              :label="allRoles.id"
              v-for="(allRoles, index) in allRolesList"
              :key="allRoles.id"
            >
              {{ allRoles.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSetUserRole">取 消</el-button>
        <el-button type="primary" @click="setUserRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { Message } from "element-ui";
import { mapState } from "vuex";
import calUserAPI from "@/api/acl/user";
export default {
  name: "user",
  data() {
    return {
      userName: "",
      roleUserName: "",
      roleUserId: "",
      orderIndex: 0,
      page: 1,
      limit: 5,
      addUserForm: {
        id: "",
        username: "",
        nickName: "",
        password: "",
      },
      dialogFormVisible: false,
      userRoleDialogVisible: false,
      isIndeterminate: false,
      removeUserList: [],
      checkAll: false,
      handleAssignRoles: [],
    };
  },
  mounted() {
    this.getCalUserInfo();
  },
  methods: {
    //获取用户信息
    async getCalUserInfo(page = 1) {
      this.page = page;
      try {
        await this.$store.dispatch("calUser/getCalUserInfo", {
          page,
          limit: this.limit,
          username: this.userName,
        });
      } catch (error) {
        Message.error(error);
      }
    },

    //统一设置设置表格列的样式
    rowStyle() {
      return "text-align:center";
    },

    //分页函数
    async handleSizeChange(limit) {
      this.limit = limit;
      await this.$store.dispatch("calUser/getCalUserInfo", {
        page: this.page,
        limit,
        username: this.userName,
      });
    },

    //查询用户
    async searchUser(flage) {
      flage && (this.userName = "");
      await this.$store.dispatch("calUser/getCalUserInfo", {
        page: this.page,
        limit: this.limit,
        username: this.userName,
      });
    },

    //添加和编辑用户
    async addOrUpdateUser() {
      try {
        await calUserAPI.reqAddOrUpdateUser(this.addUserForm);
        this.dialogFormVisible = false;
        this.getCalUserInfo();
        this.addUserForm.id
          ? Message.success("修改成功")
          : Message.success("添加成功");
        this.getCalUserInfo();
      } catch (error) {
        this.addUserForm.id
          ? Message.success("修改失败")
          : Message.success("添加失败");
      }
    },

    //选择表格单选框状态
    handleSelectionChange(val) {
      this.removeUserList = val;
    },
    //表格多选框的选择状态

    //批量删除用户
    async removeList() {
      if (this.removeUserList.length >= 1) {
        this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.handleSelectionChange.forEach((item) => {});
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      } else {
        Message.info("请选择用户");
      }
    },
    //单个删除用户
    async removeUser(row) {
      try {
        await calUserAPI.reqDeleteUser(row.id);
        Message.success(`删除用户${row.nickName}成功`);
        this.getCalUserInfo();
      } catch (error) {
        Message.success(`删除用户${row.nickName}失败`);
      }
    },

    //设置角色
    //根据用户获取角色信息
    async getUserRoleInfo({ id, username }) {
      try {
        await this.$store.dispatch("calUser/getRoleData", id);
        this.userRoleDialogVisible = true;
        this.roleUserName = username;
        this.roleUserId = id;
        this.assignRoles.length >= 1
          ? (this.isIndeterminate = true)
          : (this.isIndeterminate = false);
        this.handleAssignRoles = this.assignRoles;
      } catch (error) {
        Message.error("获取用户信息失败");
      }
    },
    //点击全选全不选
    handleCheckAllChange(val) {
      this.$store.dispatch("calUser/setAssignRoles", {
        assignRoles: val,
        allRolesList: this.allRolesList.map((item) => item.id),
      });
      this.handleAssignRoles = this.assignRoles;
      this.isIndeterminate = false;
    },
    //点击单个的选中
    handleCheckedRouleChange(val) {
      this.handleAssignRoles = val;
      this.$store.dispatch("calUser/setAssignRoles", { assignRoles: val });
      this.assignRoles.length >= 1
        ? (this.isIndeterminate = true)
        : (this.isIndeterminate = false);
    },
    //点击取消角色Diaload
    cancelSetUserRole() {
      this.userRoleDialogVisible = false;
    },
    //点击 确认角色按钮
    async setUserRole() {
      let { roleUserId } = this;
      console.log(roleUserId);
      console.log(this.assignRoles.join(","));
      try {
        await calUserAPI.reqSetAssign(roleUserId, this.assignRoles.join(","));
        Message.success("分配角色成功");
        this.userRoleDialogVisible = false;
        this.getCalUserInfo();
      } catch (error) {
        Message.success(error);
      }
    },

    //点击添加按钮打开dialog
    dialogForm(row) {
      if (row) {
        this.addUserForm = { ...row };
      } else {
        this.addUserForm = {
          id: "",
          username: "",
          nickName: "",
          password: "",
        };
      }
      this.dialogFormVisible = true;
    },
  },
  computed: {
    ...mapState("calUser", [
      "userInfo",
      "total",
      "allRolesList",
      "assignRoles",
    ]),
  },
};
</script>

<style scoped lang="scss">
.cardContainer {
  width: 90%;
  margin: 20px auto;
  .search {
    margin-bottom: 20px;
    .serachIpt {
      width: 30%;
      margin-right: 10px;
    }
  }
  .userTable {
    margin: 20px 0;
    text-align: center;
  }
}
</style>
